//
//  XLGServiceTimeInternal.m
//  etionCBLogic
//
//  Created by wangjian on 10/17/13.
//
//

#import "XLGServiceTimeInternal.h"

#import "CGWService+ChannelProocol.h"

#define VERIFY_TIME_INTERVAL 300    //每300秒获取一次网络时间用于校验
#define COUNT_TIME_INTERVAL 10    //每10秒统计一次时间

@implementation XLGServiceTimeInternal
{
    long long _verifyTime;   //网络获取到的时间
    long long _countTime;  //计时器统计的时间
    long long _verifyCount;   //用于计算校验时间间隔
    XLGServiceTimeType _curTimeType;
    BOOL _bVerifing;
    XMSTimerBlock *_timeBlock;
}

- (id)init
{
    self = [super init];
    if (self)
    {
        _curTimeType = XLGServiceTimeTypeLocal;
        [self verifyTime:YES];
        [self startCountTime];
    }
    return self;
}

- (void)dealloc
{
    [self endCountTime];
    superdealloc_mm;
}

- (NSDate *)date
{
    if([self currentTimeType] == XLGServiceTimeTypeLocal)
        return [NSDate date];
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:_verifyTime + _countTime];
    return date;
}

- (XLGServiceTimeType)currentTimeType
{
    return _curTimeType;
}

- (void)startCountTime
{
    if ([XLGContext context].m_bIsoffline == YES)
        return ;
    
    if ([XLGContext context].m_bIsofflinelogin == YES)
        return;
        
    if (_timeBlock == nil)
    {
        _timeBlock = [[XMSTimerBlock alloc] initTimerWithTimeInterval:COUNT_TIME_INTERVAL repeats:YES block:^(XMSTimerBlock *timer)
        {
            _countTime += COUNT_TIME_INTERVAL;
            _verifyCount += COUNT_TIME_INTERVAL;
            if (_verifyCount >= VERIFY_TIME_INTERVAL && _bVerifing == NO)
            {
                [self verifyTime:NO];
            }
        }];

        if([NSThread isMainThread] == YES)
        {
            [_timeBlock setFireDateFromNowToTimeInterval:COUNT_TIME_INTERVAL];
        }
        else
        {
            DispatchMainThreadAsync(^
            {
                [_timeBlock setFireDateFromNowToTimeInterval:COUNT_TIME_INTERVAL];
            });
        }
    }
}

- (void)endCountTime
{
    [self stopRequest];
    [_timeBlock invalidate];
    ReleaseObj(_timeBlock);
}

- (XLGResult*)getServiceTime
{
    XLGResult *result = [[self service] sendChannelProtocol:^CProtocolBase *
    {
        return [[[XLGServiceTimeChannelProtocol new] autorelease_mm] serviceTimeProtocol];
    }];
    return result;
}

- (void)verifyTime:(BOOL)isCountInterrupted
{
    [super requestThreadBlock:^
    {
        if ([XLGContext context].m_bIsoffline == YES)
            return ;
        
        if ([XLGContext context].m_bIsofflinelogin == YES)
            return;
        
        if (self.isCanRequest == NO)
            return;

        _verifyCount = 0;
        if (_bVerifing == YES)
        {
           return;
        }
        _bVerifing = YES;
        BOOL bVerifySuccess = YES;
        __block NSInteger nThisresult = 0;
        __block long long thisTime = 0;

        XLGResult* r = [self getServiceTime];
        nThisresult = r.outResult;
        thisTime = [(NSNumber*)r.outObj longLongValue];
        
        if (nThisresult == YES)
        {
            _curTimeType = XLGServiceTimeTypeService;
            thisTime /= 1000;
            
            [NSNotificationCenter postNotification:XLGServiceTimeCheckServiceTimeSuccess userInfo:@{XLGServiceTimeCheckServiceTimeSuccessTimeKey:@(thisTime)}];
        }
        else if (isCountInterrupted == NO && _curTimeType == XLGServiceTimeTypeService)
        {
            bVerifySuccess = NO;
        }
        else
        {
            _curTimeType = XLGServiceTimeTypeLocal;
            thisTime = [[NSDate date] timeIntervalSince1970];
        }
        
        _bVerifing = NO;
        if (bVerifySuccess == YES)
        {
            _verifyTime = thisTime;
            _countTime = 0;
        }
    }];
}

@end
